import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:lite_clock/bloc/app_bloc.dart';
import 'package:lite_clock/bloc/time_bloc.dart';
import 'package:lite_clock/ui/splash_page.dart';
import 'package:lite_clock/util/storage_util.dart';
import 'package:screen/screen.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await StorageUtil.setBool('firstRun', true);

  //隐藏状态栏
  await SystemChrome.setEnabledSystemUIOverlays([]).then((_) async {
    ///时钟样式索引
    final _clockIndex = await StorageUtil.getInt('clockIndex') ?? 0;

    ///显示农历
    final _showC = await StorageUtil.getBool('showC') ?? false;

    ///显示电池
    final _showB = await StorageUtil.getBool('showB') ?? true;

    ///自动移动
    final _move = await StorageUtil.getBool('move') ?? true;

    ///时钟颜色
    final _clockColor = await StorageUtil.getInt('clockColor') ?? 0xFF9F7CFF;

    ///点缀颜色
    final _dotColor = await StorageUtil.getInt('dotColor') ?? 0xFFF89037;

    runApp(
      MultiBlocProvider(
        providers: [
          BlocProvider(
            create: (_) => AppBloc(
              AppMag(
                clockColor: _clockColor,
                dotColor: _dotColor,
                clockIndex: _clockIndex,
                isMoveClock: _move,
                showBattery: _showB,
                showChineseCalender: _showC,
              ),
            ),
          ),
          BlocProvider(create: (_) => TimeBloc()),
        ],
        child: const MyApp(),
      ),
    );
  });
}

class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);

  ///第一次运行
  _firstRun(BuildContext context) async {
    if (await StorageUtil.getBool('firstRun')) {
      //状态栏透明
      SystemUiOverlayStyle systemUiOverlayStyle =
          SystemUiOverlayStyle(statusBarColor: Colors.transparent);

      SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);

      //屏幕常亮
      await Screen.keepOn(true);

      ///强制横屏
      await SystemChrome.setPreferredOrientations(
          [DeviceOrientation.landscapeRight, DeviceOrientation.landscapeLeft]);

      context.bloc<TimeBloc>().start();
    }
  }

  @override
  Widget build(BuildContext context) {
    _firstRun(context);

    return BlocBuilder<AppBloc, AppMag>(
      buildWhen: (p, c) => p.clockColor != c.clockColor,
      builder: (c, app) {
        return MaterialApp(
          title: 'Lite clock',
          debugShowCheckedModeBanner: false,
          theme: ThemeData.light().copyWith(
            bottomAppBarColor: Colors.black,
            primaryColor: Color(app.clockColor),
            dividerColor: Color(app.dotColor),
          ),
          home: const SplashPage(),
        );
      },
    );
  }
}
